<template>
  <div class="user-bottom">
    <header>
      <h2>用户列表</h2>
      <el-button
        round
        type="primary"
        loading-icon="Eleme"
        :loading="isLoading"
        @click="handleAddUser"
        >添加用户</el-button
      >
    </header>
    <!-- 骨架屏区域 -->
    <Skeleton :count="15" v-if="!userStore.userList"></Skeleton>
    <!-- 表格区域 -->
    <el-table class="table" style="width: 100%" :data="dataList" border v-else>
      <el-table-column type="selection" align="center" />
      <el-table-column type="index" label="序号" align="center" width="60px" />
      <el-table-column label="用户名" prop="username" align="center" width="160" />
      <el-table-column label="真实姓名" prop="realname" align="center" width="120px" />
      <el-table-column label="手机号" prop="phonenumber" align="center" width="160px" />
      <el-table-column label="状态" prop="state" align="center" width="70px">
        <template #default="{ row: { state } }">
          <el-tag :type="state === 1 ? 'success' : 'danger'">{{
            state === 1 ? '启用' : '禁用'
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" show-overflow-tooltip prop="createtime" align="center">
        <template #default="{ row: { createtime } }">{{ formateDate(createtime) }}</template>
      </el-table-column>
      <el-table-column label="更新时间" show-overflow-tooltip prop="updatetime" align="center">
        <template #default="{ row: { updatetime } }">{{ formateDate(updatetime) }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150px">
        <template #default="{ row }">
          <el-button text type="primary" icon="Edit" size="small" @click="handleUpdate(row)"
            >编辑</el-button
          >
          <el-button text type="danger" icon="Delete" size="small" @click="handleDelete(row._id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <footer v-if="userStore.userList">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :small="true"
        layout=" sizes, prev, pager, next, jumper,total"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </footer>
    <UserDialog ref="DialogDOM"></UserDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useUserStore } from '@/store/userStore'
import Skeleton from '@/components/global/Skeleton.vue'
import UserDialog from './components/UserDialog.vue'
import { formateDate } from '@/utils/formatTime'
import type { UserListResOfDataArr } from '@/interface/user/userType'
let props = defineProps(['searchData'])

const userStore = useUserStore()
// const dataList = ref<UserListResOfDataArr>()
// const totalCount = ref(0)
const page = ref(1)
const pageSize = ref(5) //测试为1，实际5
const isLoading = ref<boolean>(false)
const DialogDOM = ref() //获取弹出层实例

// 后期数据添加删除的时候，页面并没有更新，因此将数据设计为计算属性，依赖pinia中的数据源改变而改变
// @ts-ignore
const dataList = computed(
  () => userStore.userList,
  (newVal: UserListResOfDataArr) => {
    return newVal
  }
)
// @ts-ignore
const totalCount = computed(
  () => userStore.userListTotal,
  (newVal: number) => {
    return newVal
  }
)

// 因为这里都是请求store中的方法获取数据，因此可以将方法抽离进行封装
/**
 *
 * @param data 选传，不传默认传递page和pageSize
 */
const fetchUserList = async (data: any = {}) => {
  try {
    let config = {
      page: page.value,
      pageSize: pageSize.value
    }
    config = { ...config, ...data }
    console.log('config', config)

    let res = await userStore.getUserList(config)
    if (res?.code === -1) {
      // @ts-ignore
      ElMessage({
        type: 'error',
        message: res?.message
      })
      return
    }
    // dataList.value = userStore.userList as UserListResOfDataArr
    // totalCount.value = userStore.userListTotal as number
    // console.log(dataList.value)
  } catch (error) {}
}

// 处理分页器回调
const handleSizeChange = () => {
  fetchUserList(props.searchData)
}
const handleCurrentChange = () => {
  fetchUserList(props.searchData)
}

// 删除用户
const handleDelete = (id: number) => {
  userStore.deleteUserListItem(id)
}

// 添加用户
const handleAddUser = () => {
  // 添加用户不需要预览数据，因此只需要传递一个显示弹窗即可
  DialogDOM.value?.changeDialogVisible(true)
}

// 编辑按钮
const handleUpdate = (val: any) => {
  // 编辑按钮复用添加用户的弹窗组件使用，需要将数据传递过去显示预览
  // 触发时机就是点击显示弹窗的时候需要将数据传递过去
  const isEdit = true
  DialogDOM.value?.changeDialogVisible(true, isEdit, val)
}

// 父组件通过实例访问该方法实现兄弟组件交互
defineExpose({
  fetchUserList
})

userStore.$onAction(({ name, after }) => {
  after(() => {
    // 确保是该action已经执行完毕返回结果
    if (name === 'addUserItem' || name === 'deleteUserListItem') {
      // 只有在这写action方法执行完毕后才操控页表
      page.value = 1
    }
  })
})

onMounted(async () => {
  fetchUserList()
})
</script>

<style lang="scss" scoped>
.user-bottom {
  width: 100%;
  height: 100%;
}
header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 10px;
  h2 {
    font-size: 20px;
  }
}
.table {
  .el-button {
    padding: 0;
  }
}
footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 15px;
}
</style>
